import { getToken, setToken, getUser, setUser, removeCookie } from '@/utils/auth'
import { login, getUserInfo, logout } from '@/api/login'

const user = {
    state: {
        token: getToken(),
        user: getUser()
    },

    mutations: {
        SET_TOKEN (state, token) {
            state.token = token
            setToken(token)
        },
        SET_USER (state, user) {
            console.log("setUser", user)
            state.user = user
            setUser(user)
        }
    },

    actions: {
        // 登录获取token
        Login ({ commit }, form) {
            return new Promise((resolve, reject) => {
                
                login(form.username.trim(), form.password).then(response => {
                    const resp = response.data
                    commit('SET_TOKEN', resp.data.token)
                    // 通知组件更新成功
                    resolve(resp)
                }).catch (error => {
                    reject(error)
                }) 

            })
        },
        // 通过token获取用户信息
        GetUserInfo ({ commit, state }) {

            return new Promise((resolve, reject) => {
                getUserInfo(state.token).then(response => {
                    const respUser = response.data
                    console.log("respUser: " + respUser)
                    commit('SET_USER', respUser.data)
                    resolve(respUser)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 退出登录
        Logout ({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(response => {
                    const resp = response.data
                    commit('SET_TOKEN', '')
                    commit('SET_USER', null)
                    resolve(resp)
                }).catch(error => {
                    reject(error)
                })
            })
        }
    }
}

export default user